# -*- coding: utf-8 -*-
# @Time    : 2024/7/7 23:54
# @Author  : wangwei
# @File    : AppKeyword_bak.py
import json
import os
import threading
import time
from common.Logger import logger
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy

from common.decs import relations


class Appkeyword:
    logger = logger
    relations_dict={}

    def __init__(self, host="127.0.0.1", port=4723):

        self.caps = None
        self.appium_server_url = f'http://{host}:{port}/wd/hub'
        # self.caps["platformName"] = "Android"
        # self.caps["deviceName"] = "127.0.0.1:7555"
        # self.caps["appPackage"] = "com.tencent.mobileqq"
        # self.caps["appActivity"] = ".activity.SplashActivity"
        # self.caps["noReset"] = "true"
        # self.caps["ensureWebviewsHavePages"] = True
        self.driver: webdriver.Remote = None

    @relations
    def __find_ele(self, locator: str = ""):
        try:
            if locator.startswith("/") or locator.startswith("("):
                ele = self.driver.find_element(AppiumBy.XPATH, locator)
                self.logger.info(f"通过【XPATH】定位元素【{locator}成功，成功返回元素】")
            elif locator.__contains__(":id/"):
                ele = self.driver.find_element(AppiumBy.ID, locator)
                self.logger.info(f"通过【ID】定位元素【{locator}成功，成功返回元素】")
            else:
                ele = self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, locator)
                self.logger.info(f"通过【ACCESSIBILITY_ID】定位元素【{locator}成功，成功返回元素】")
            return ele
        except Exception as e:
            self.logger.exception(f"定位元素【{locator}操作失败，报错信息：{e.__str__()}】")
            return None

    @relations
    def click(self, locator: str = ""):
        try:
            ele = self.__find_ele(locator=locator)
            ele.click()
            self.logger.info(f"点击元素【{locator}操作成功】")
        except Exception as e:
            self.logger.exception(f"点击元素【{locator}操作失败，报错信息：{e.__str__()}】")

    @relations
    def input(self, locator: str = "", value: str = ""):
        try:
            ele = self.__find_ele(locator=locator)
            ele.clear()
            ele.click()
            ele.send_keys(value)
            self.logger.info(f"向元素【{locator}中输入{value}成功】")
        except Exception as e:
            self.logger.exception(f"向元素【{locator}中输入{value}失败，报错信息：{e.__str__()}】")


    def sleep(self, timedata="1"):
        wait_time = float(timedata)
        time.sleep(wait_time)
        self.logger.info(f"等到{timedata}s")

    def quit(self):
        self.driver.quit()
        self.logger.info(f"driver成功退出")

    @relations
    def stop_appium(self, port: str = "4723"):
        try:
            get_pro = os.popen(f"netstat -ano|findstr {port}").read().split(" ")[-1]
            print(get_pro)
            if get_pro:
                os.system(f"taskkill /f /pid {get_pro}")
            self.logger.info(f"appium关闭成功")
        except Exception as e:
            self.logger.exception(f"appium关闭失败,失败信息：{e.__str__()}")

    @relations
    def start_appuim(self, port: str = "4723"):
        self.stop_appium()
        try:
            def __run_appuim():
                os.system("adb connect 127.0.0.1:7555")
                os.system(
                    rf'node "C:\Program Files\Appium\resources\app\node_modules\appium\build\lib\main.js" -p {port} --chromedriver-executable dd')

            th = threading.Thread(target=__run_appuim)
            th.start()
            self.logger.info("appium正在启动,即将等待10s")
            self.sleep("10")
            self.logger.info(f"appium启动成功")
        except Exception as e:
            self.logger.exception(f"appium启动失败,失败信息：{e.__str__()}")

    @relations
    def start_app(self,
                  conf: str = '{"platformName": "Android", "deviceName": "127.0.0.1:7555", "appPackage": "com.tencent.mobileqq", "appActivity": ".activity.SplashActivity", "noReset": "true", "ensureWebviewsHavePages": "true","unicodeKeyboard":"true","resetKeyboard":"true"}'):
        try:
            self.caps = json.loads(conf)
            print(type(self.caps))
            self.caps["udid"] = self.caps.get("deviceName")
            self.driver = webdriver.Remote(self.appium_server_url, self.caps)
            self.driver.implicitly_wait(30)
            self.logger.info(f"app启动成功")
        except Exception as e:
            self.logger.exception(f"app启动失败,失败信息：{e.__str__()}")

    @relations
    def assert_page_contains(self, text_content: str = ""):
        page_source = self.driver.page_source
        if page_source.__contains__(text_content):
            self.logger.info(f"测试通过，页面中包含{text_content}")
            return True
        else:
            self.logger.exception(f"测试失败，{self.driver.page_source}中不包含{text_content}")
            return False

    @relations
    def gettext(self, locator: str = "",variable_name="text"):
        try:
            ele = self.__find_ele(locator=locator)
            text=ele.text
            self.relations_dict["variable_name"]=text
            self.logger.info(f"通过定位方式【{locator}】,获取文本值成功")
            return text
        except Exception as e:
            self.logger.exception(f"通过定位方式【{locator}】,获取文本值失败")
            return None

    @relations
    def assert_text(self, except_str="", actual_str=""):
        if except_str == actual_str:
            self.logger.info("测试通过,文本值与预期一致")
            return True
        else:
            self.logger.exception(f"断言失败，预期值：{except_str}，实际值：{actual_str}")
            return False

    @relations
    def keyevent(self, keycode='66'):
        try:
            keycode = int(keycode)
        except:
            keycode = 66

        self.driver.keyevent(keycode)

    # @relations
    # def get_screenshot_as_png(self):
    #     try:
    #         if self.driver:
    #             self.driver.get_screenshot_as_png()
    #             return self.logger.info(f"【截图全屏】操作成功")
    #         else:
    #             pass
    #     except Exception as e:
    #         self.logger.exception(f"【截图全屏】操作失败")
    #         return None
